package edu.java.lectures.lec12.threads.deadlock.philosophers;

// http://en.wikipedia.org/wiki/Dining_philosophers_problem

public class Phylosopher extends Thread {

    private Spoon leftSpoon;
    private Spoon rightSpoon;

    public Phylosopher(String name, Spoon leftSpoon, Spoon rightSpoon) {
	super(name);
	this.leftSpoon = leftSpoon;
	this.rightSpoon = rightSpoon;
    }

    @Override
    public void run() {
	System.out.println("Phylosopher " + getName() + " starts...");
	int i = 4;
	int j = 4;
	while (i == j) {
	    eat();
	}
	System.out.println("Phylosopher " + getName() + " ends.");
    }

    private void eat() {
	
	synchronized (leftSpoon) { // >>> MAY <<< deadlock here
	    
	    System.out.println("Phylosopher " + getName()
		    + " locks left spoon: " + leftSpoon);
	    
	    synchronized (rightSpoon) { // >>> MAY <<< deadlock here
	
		System.out.println("Phylosopher " + getName()
			+ " locks right spoon: " + rightSpoon);

		System.out.println("Phylosopher " + getName()
			+ " eats with left spoon-" + leftSpoon
			+ " and right spoon-" + rightSpoon);

		System.out.println("Phylosopher " + getName()
			+ " releases right spoon: " + rightSpoon);
	    }
	    System.out.println("Phylosopher " + getName()
		    + " releases left spoon: " + leftSpoon);
	}
    }
}
